package system

import (
	"WchimeGinSystem/models"
	"WchimeGinSystem/utils"
	"WchimeGinSystem/utils/errmsg"

	"github.com/gin-gonic/gin"
)

type CreateUserReq struct {
	Username  string `json:"username" binding:"required"`  // 用户名
	Password1 string `json:"password1" binding:"required"` // 密码
	Password2 string `json:"password2" binding:"required"` // 确认密码
}

// Login
// @Summary 创建用户
// @Description 创建用户
// @Tags 创建用户
// @Accept json
// @Produce json
// @Param req body CreateUserReq true "入参"
// @Success 200 {string} string "ok"
// @Failure 400 {string} string "bad request"
// @Failure 500 {string} string "Internal Server Error"
// @Router /create_user [post]
// @Security ApiKeyAuth
func CreateUser(c *gin.Context) {

	var body CreateUserReq

	if err := c.ShouldBindJSON(&body); err != nil {

		utils.RespContext(c).ErrorResp(nil, errmsg.ERROR_PARAMS_VALID, "")
		return
	}

	if body.Password1 != body.Password2 {

		utils.RespContext(c).ErrorResp(nil, errmsg.ERROR_DOUBLE_PWD, "")
		return
	}

	hash_pwd, err1 := utils.HashPassword(body.Password1)
	if err1 != nil {
		utils.RespContext(c).ErrorResp(nil, errmsg.ERROR_BASE, "")
		return
	}

	CreateUserFunc(body.Username, hash_pwd, c)

}

func CreateUserFunc(username string, hash_pwd string, c *gin.Context) {

	var u models.User
	var err error
	err = models.DB.Where("username = ?", username).First(&u).Error
	if err != nil {

		user := models.User{
			Username: username,
			Password: hash_pwd,
			Nickname: username,
		}
		err = models.DB.Create(&user).Error
		if err != nil {
			utils.RespContext(c).ErrorResp(nil, errmsg.ERROR_BASE, "")
			return
		}
		utils.RespContext(c).SuccessResp(user)
	} else {
		utils.RespContext(c).ErrorResp(nil, errmsg.ERROR_USER_EXISTS, "")
		return
	}

}
